<?php
/**
 * @title 43. 字符串相乘 - 迭代
 * @author start2004
 */

class Solution {

    /**
     * @param String $num1
     * @param String $num2
     * @return String
     */
    function multiply($num1, $num2) {
        /**
         * @since 2020-07-21 极端情况排除
         */
        if($num1 == 0 OR $num2 == 0){
            return "0";
        } else {}

        /**
         * @since 2020-07-21 长度
         */
        $len1 = strlen($num1);
        $len2 = strlen($num2);

        /**
         * @since 2020-07-21 结果集
         */
        $result = array_fill(0, $len1+$len2, 0);

        /**
         * @since 2020-07-21 低位依次相乘
         */
        $addI = $len1;
        for ($i=$len1-1; $i>=0; $i--){
            $addJ = $addI+$len2-1;
            for($j=$len2-1; $j>=0; $j--){
                /**
                 * @since 2020-07-21 放到对位置上
                 */
                $n = $num1[$i] * $num2[$j];
                $result[$addJ] += $n;
                $addJ--;
            }
            $addI--;
        }
        // return $result;

        /**
         * @since 2020-07-21 处理进位
         */
        $list = [];
        $add = 0;
        for ($i=count($result)-1; $i>=0; $i--){
            $num = $result[$i]+$add;

            $b = $num%10;
            $add = ($num-$b)/10;
            $result[$i] = $b;
        }

        /**
         * @since 2020-07-21 最高位可能为0
         */
        if($result[0] == 0){
            unset($result[0]);
        } else {}

        /**
         * @return
         */
        return implode("", $result);
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.21_3.php
 */
$datas = [
    // ["1234567890123456789012345678901234567890", "987654321987654321987654321987654321"],
    ["45", "67"],
    // ["2", "3"],
    // ["123", "456"],
    // ["99", "99"],
    // ["100", "100"],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->multiply($data[0], $data[1]);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
